<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button class="set">设置</button>
    <button class="get">输出</button>
</body>
<script>
    // cookie的创建

    // 1. cookie的存取都依赖于 document.cookie
    // 2. cookie是以键值对(key=val)形式存在的字符串
    // 3. cookie是一条一条的存储的
    // 4. cookie 可以设置存储路径  和  过期时间(默认浏览器关闭 过期)

    var set = document.getElementsByClassName("set")[0];
    var get = document.getElementsByClassName("get")[0];

    set.onclick = function(){
        /* document.cookie = "user=4564"
        document.cookie = "password=6689" */

        //设置时间
        /* var date = new Date();
        date.setDate(date.getDate() + 7);
        document.cookie = "user=12356;expires=" + date.toUTCString();
        document.cookie = "password=4645;expires=" + date.toUTCString(); */

        //设置存储路径，实现跨页面访问
        /* var date = new Date();
        date.setFullYear(date.getFullYear() + 7);
        document.cookie = "user=12356;expires=" + date.toUTCString() + ";path=/";
        document.cookie = "password=4645;expires=" + date.toUTCString() + ";path=/"; */

        setCookie("user" , "32113" , 7);
    }

    get.onclick = function(){
        console.log(getCookie("user"));
    }



    // 封装
    function setCookie(key , val , day , path = "/"){
        if(day != undefined){
            var date = new Date();
            date.setDate(date.getDate() + day);
            document.cookie = key + "=" + val + ";expires=" + date.toUTCString() + ";path=" + path;
        }else{
            document.cookie = key + "=" + val + ";path=" + path;
        }
    }

    function getCookie(key){
        var cookie = document.cookie;
        if(cookie){
            var list = cookie.split(";");
            for(var i = 0 ; i < list.length ; i++){
                var item = list[i];
                var attr = item.split("=")[0];
                var val = item.split("=")[1];
                if(key === attr){
                    return val;
                }
            }
        }
        return "";
    }
</script>
</html>